<?php
//提供数据(分数, 头像, 昵称, openid)
$score = $_GET["score"];
$nickname = $_GET["nickname"];
$openid = $_GET["openid"];
$headimgurl = $_GET["headimgurl"];

//表的设计
//主键: openid, varchar, 50
//头像: headimgurl, varchar, 500
//分数: score, int
//昵称: nickname, varchar, 20

//最好成绩
$bestScore = 0;
$bestRank = 0;

//数据库的操作
$mysqli = new mysqli("vyuyzmoglbsq.rds.sae.sina.com.cn", "fuxiaohui", "123456", "h7", 10346);

//connect_errno: 错误编号, 如果是0, 代表没有错误
//connect_error: 错误信息
if ($mysqli->connect_errno) {
  exit("数据库连接失败:".$mysqli->connect_error);
}

$mysqli->set_charset("utf8");

//根据openid, 查询信息
$sql = "select * from money where openid = '{$openid}'";
$result = $mysqli->query($sql);
if ($result->num_rows == 0) {
  //第一次玩
  //插入数据
  $sql = "insert into money (openid, score, nickname, headimgurl) values ('{$openid}', $score, '{$nickname}', '{$headimgurl}')";
	if ($mysqli->query($sql) == FALSE) {
		$mysqli->close();
	  exit("插入失败");
	}
	$bestScore = $score;
} else {
	//老手
	//获取之前的数据
	$row = $result->fetch_object();
	if ($row->score > $score) {
		//没有破纪录
		$bestScore = $row->score;
	} else {
		//新记录
		//更新数据
		$sql = "update money set score = $score where openid = '{$openid}'";
		if ($mysqli->query($sql) == FALSE) {
			$mysqli->close();
			exit("更新失败");
		}
		$bestScore = $score;
	}
}

//查询排名
$sql = "select * from money where score > {$bestScore}";
$result = $mysqli->query($sql);
if ($result->num_rows == 0) {
  $bestRank = 1;
} else {
	$bestRank = $result->num_rows + 1;
}

$mysqli->close();

//返回json数据
$arr = array(
	"bestScore"=>$bestScore,
	"bestRank"=>$bestRank
);

echo json_encode($arr);


?>